package dev.ece.suit.loader.models.fbx;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class FBXPose {

	public static final String POSE = "Pose";
	
	public static final String TYPE = "Type";
	
	public static final String BIND_POSE = "BindPose";
	
	private long id;
	
	private String type;
	
	private FBXPoseNode[] poseNodes;
	
	public static FBXPose[] parseFBXPose(List<FBXElement> elements) throws IOException {
		FBXPose[] poses = null;
		if(elements != null && !elements.isEmpty()) {
			poses = new FBXPose[elements.size()];
			FBXElement element = null;
			FBXElement type = null;
			for(int i=0; i<poses.length; i++) {
				poses[i] = new FBXPose();
				element = elements.get(i);
				poses[i].id = (Long) element.getProperties()[0].getValue();
				type = element.findFirstChild(TYPE);
				if(type != null) {
					poses[i].type = (String) type.getProperties()[0].getValue();
				}
				poses[i].poseNodes = FBXPoseNode.parseFBXPoseNode(element.findChildren(FBXPoseNode.POSE_NODE), poses[i]);
			}
		}
		return poses;
	}

	public static void connectFBXJointModel(Map<Long, List<FBXConnection>> connections, FBXPose[] poses, FBXJoint[] joints, FBXModel[] models) {
		if(poses != null) {
			Map<Long, FBXJoint> map = FBXJoint.toFBXJointMap(joints);
			Map<Long, FBXModel> modelmap = FBXModel.toFBXModelMap(models);
			List<FBXConnection> conns = null;
			FBXJoint joint = null;
			FBXModel model = null;
			for(FBXPose pose: poses) {
				if(pose.getPoseNodes() != null) {
					for(FBXPoseNode poseNode: pose.getPoseNodes()) {
						conns = connections.get(poseNode.getId());
						if(conns != null) {
							for(FBXConnection conn: conns) {
								joint = map.get(conn.getTo());
								if(joint != null) {
									joint.setPoseNode(poseNode);
								}
								model = modelmap.get(conn.getTo());
								if(model != null) {
									model.getPoseNodes().add(poseNode);
								}
							}
						}
					}
				}
			}
		}
	}
	
	public long getId() {
		return id;
	}

	public boolean isBindPose() {
		return StringUtils.equals(FBXPose.BIND_POSE, this.getType());
	}
	
	public FBXPoseNode[] getPoseNodes() {
		return poseNodes;
	}

	public String getType() {
		return type;
	}
	
}
